<template>
	<div class="required_course_container">
		<div class="list" v-loading="loading">
			<template v-if="tableListData.length > 0">
				<study-course v-for="(item, index) in tableListData" :key="index" :data="item">
					<el-button size="small" type="primary" @click="handleStartStudy(item)">开始学习</el-button>
					<template v-if="!item.isCollect">
						<el-button size="small" type="info" @click="handleCollectCourse(item)">未收藏</el-button>
					</template>
					<template v-else>
						<el-button size="small" type="success" @click="handleCollectCourse(item)">已收藏</el-button>
					</template>
				</study-course>
			</template>
			<el-empty v-else :image-size="150" description="暂无数据"></el-empty>
		</div>
		<div class="page" v-if="dataCount > 0">
			<sw-pagination v-bind="pageLayout" :total="dataCount" :page.sync="queryData.page" :limit.sync="queryData.limit" @change="queryTableData()"></sw-pagination>
		</div>
	</div>
</template>

<script>
import lodash from 'lodash';
import { mapGetters } from 'vuex';
import listMixins from '@/mixins/listMixins';
import studyCourse from '@/views/common/studyItem';
import { getChapterList } from '@/api/course/sysCourseChapter';
import { getCourseStudyPageList } from '@/api/course/sysCourseStudent';
import { queryCollectList, addedCollect, deleteCollect, isCollects } from '@/api/front/myCollectInfo';
export default {
	mixins: [listMixins],
	components: { studyCourse },
	data() {
		return {
			collectData: []
		};
	},
	computed: {
		...mapGetters(['userInfo']),
		userId() {
			return this.userInfo.id;
		},
		listFunction() {
			return eval(getCourseStudyPageList);
		},
		requestParams() {
			return { ...this.queryData, studentId: this.userId };
		},
		pageLayout() {
			if (this.isMobile) {
				return { isSizes: false, isJumper: false, layout: 'prev, pager, next' };
			} else {
				return { isSizes: true, isJumper: true, layout: '' };
			}
		},
		tableListData() {
			return this.tableData.map((item) => {
				let data = this.collectData.find((n) => n.resId === item.courseId);
				if (!data) {
					return { ...item };
				} else if (data.isCollect === 'Y') {
					return { ...item, isCollect: true };
				} else if (data.isCollect === 'N') {
					return { ...item, isCollect: false };
				}
			});
		}
	},
	watch: {
		async tableData(arr) {
			this.getCollectedData(arr);
		}
	},
	mounted() {
		this.getChapterNodes();
	},
	methods: {
		//获取课程章节
		async getChapterNodes() {
			let params = { pid: '0', courseId: 270 };
		},

		//获取已收藏数据
		async getCollectedData(arr) {
			let resIds = arr.map((n) => n.courseId);
			let params = { resType: '1', resIds: resIds.join() };
			let result = await isCollects(params).then((res) => res.data);
			if (result.code == '0') {
				this.collectData = result.data || [];
			}
		},

		//开始学习
		async handleStartStudy(item) {
			let params = { pid: 0, courseId: item.courseId };
			let path = `/front/trainingResources/${item.courseId}`;
			let result = await getChapterList(params).then((res) => res.data);
			if (result.code === '0') {
				let datas = result.data || [];
				let chapters = this.$treeAddedSort(datas, 'childList');
				let chapterArr = this.$treeToFlat(chapters, 'childList');
				let chapterNodes = chapterArr.filter((n) => n.type === '2');
				let sortNodes = lodash.orderBy(chapterNodes, ['sort'], ['asc']);
				let juageParams = { courseId: item.courseId, nodes: sortNodes };
				let unfinish = await this.$store.dispatch('getUnlearnChapter', juageParams);
				if (juageParams.nodes.length === 0) {
					this.$message.warning('该课程尚未搭建课程章节，请联系管理员添加！');
				} else if (lodash.isEmpty(unfinish)) {
					this.$router.push({ path, query: { type: 'exam' } });
				} else {
					let drama = unfinish.id;
					this.$router.push({ path, query: { type: 'learn', drama } });
				}
			}
		},

		//获取收藏数据
		async getCollectData(data) {
			let object = { page: 1, limit: 1, resId: data.courseId };
			let params = { ...object, resType: 1, createBy: this.userId };
			let result = await queryCollectList(params).then((res) => res.data);
			if (result.code === '0') {
				let datas = this.$detailData(result.data);
				return Promise.resolve(!lodash.isEmpty(datas) ? datas.id : '');
			}
		},

		//收藏/取消收藏课程
		async handleCollectCourse(data) {
			let collectId = await this.getCollectData(data);
			if (!collectId) {
				this.addedCollectRequest(data);
			} else {
				this.deleteCollectRequest(collectId);
			}
		},

		//添加收藏课程请求
		async addedCollectRequest(data) {
			let extFiled = JSON.stringify(data.sysCourseInfo);
			let params = { resType: 1, resId: data.courseId, extFiled };
			let result = await addedCollect(params).then((res) => res.data);
			if (result.code === '0') {
				this.$message.success('收藏成功');
				this.getCollectedData(this.tableData);
			}
		},

		//取消收藏课程请求
		async deleteCollectRequest(id) {
			let result = await deleteCollect(id).then((res) => res.data);
			if (result.code === '0') {
				this.$message.success('取消收藏成功');
				this.getCollectedData(this.tableData);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.required_course_container .page {
	padding: 16px;
}
</style>
